<template>
  <a-table table-layout="fixed" :scroll="{ x: '100%' }" :data-source="data" :pagination="pagination" v-bind="$attrs"
    bordered @change="onChange">
    <template v-if="props.isExtra" #expandedRowRender="{ record }">
      <slot name="expandedRow" :record="record" />
    </template>
  </a-table>
</template>

<script lang="ts">
export default {
  inheritAttrs: false,
};
</script>

<script setup lang="ts">
import type { IPageData } from "@/types/table";

const props = withDefaults(
  defineProps<{
    api?: undefined | ((...args: unknown[]) => PromiseLike<IPageData>);
    params?: Record<string, unknown>;
    auto?: boolean;
    loading?: boolean;
    sort?: string;
    isExtra?: boolean;
  }>(),
  {
    api: undefined,
    auto: true,
    loading: false,
    isExtra: false,
    sort: "create_time",
    params: () => ({}),
  }
);
const data = ref<unknown[]>([]);
const pagination = reactive({
  position: "bottomRight",
  showQuickJumper: true,
  showSizeChanger: true,
  showLessItems: true,
  showTotal: (total: number) => `共 ${total} 条`,
  size: "default",
  total: 0,
  current: 1,
  pageSize: 10,
});

onMounted(() => {
  props.auto && getData();
});
defineExpose({
  getData,
  data
});
async function getData(research = false) {
  if (!props.api) {
    return;
  }
  if (research) {
    pagination.current = 1;
  }
  const { current: page, pageSize: limit } = pagination;
  const params = {
    order: "desc",
    sidx: props.sort,
    ...props.params,
    page,
    limit,
  };
  try {
    const { list, total } = await props.api(params);
    data.value = list;
    pagination.total = total;
  } catch (error) {
    console.log(error);
  }
}

function onChange({
  pageSize,
  current,
}: {
  pageSize: number;
  current: number;
}) {
  pagination.current = current;
  pagination.pageSize = pageSize;
  getData();
}
</script>

<style lang="less"></style>
